/*
 * @Author       : 魏威 <1209562577@qq.com>
 * @Date         : 2021-09-13 19:58 周1
 * @Description  : auth-context
 */

import * as auth from 'auth-provider';
import React, { ReactNode, useState } from 'react';
import { User } from 'screens/project-list/search-panel';
import { useMount } from 'utils';
import { http } from 'utils/http';

interface AuthForm {
  username: string;
  password: string;
}

const bootstrapUser = async () => {
  let user = null;
  const token = auth.getToken();
  if (token) {
    const data = await http('me', { token });
    user = data.user;
  }
  return user;
};

const AuthContext = React.createContext<
  | {
      user: User | null;
      login: (form: AuthForm) => Promise<void>;
      register: (form: AuthForm) => Promise<void>;
      logout: () => Promise<void>;
    }
  | undefined
>(undefined);
AuthContext.displayName = 'AuthContext';

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);

  // 初始化
  useMount(() => {
    bootstrapUser().then(setUser);
  });
  // const login = (form: AuthForm) => auth.login(form).then((user) => setUser(user));
  // point free编程方式
  const login = (form: AuthForm) => auth.login(form).then(setUser);
  const register = (form: AuthForm) => auth.register(form).then(setUser);
  const logout = () => auth.logout().then(() => setUser(null));
  return (
    <AuthContext.Provider
      value={{ user, login, register, logout }}
      children={children}
    />
  );
};

export const useAuthContext = () => {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error('useAuthContext必须在Provider中使用');
  }
  return context;
};
